/*
 * 创建日期 Nov 2, 2009
 *
 * 成都天和软件公司
 * 电话：028-85425861
 * 传真：028-85425861-8008
 * 邮编：610041 
 * 版权所有
 */
package  org.fantasy.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *  功能说明:处理AJAX应用的中文问题；使用本过滤器，提交AJAX请求时必须使用POST方式！
 * @author: 王辉
 * @version: 1.0
 * @since Nov 2, 2009
 */
public class AjaxEncodeFilter implements Filter {

	private static final Log log = LogFactory.getLog(AjaxEncodeFilter.class);
	private static String AJAX_POST_ENCODING = "UTF-8";

	public void init(FilterConfig arg0) throws ServletException {

	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		String requestedWith = request.getHeader("X-Requested-With");
		String contentType = request.getContentType();
		if ("XMLHttpRequest".equals(requestedWith) && contentType != null
				&& contentType.startsWith("application/x-www-form-urlencoded")) {
			request.setCharacterEncoding(AJAX_POST_ENCODING);
			response.setCharacterEncoding(AJAX_POST_ENCODING);
		}
		log.debug("CharacterEncoding :" + request.getCharacterEncoding());
		filterChain.doFilter(request, response);

	}

	public void destroy() {

	}
}
